<template>
  <div>
    <el-form :model="queryParams" ref="queryForm" :inline="true">
      <el-form-item label="流程名称">
        <el-input v-model="queryParams.flowName" placeholder="请输入流程名称" clearable size="small"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="料单类型">
        <el-select v-model="queryParams.receiptTypeOpt" placeholder="请选择料单类型" clearable size="small">
          <el-option v-for="dict in receiptTypeOptOptions" :key="dict.dictValue" :label="dict.dictLabel"
            :value="dict.dictValue" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="small" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="small" @click="resetQuery">重置</el-button>
        <el-button type="primary" size="small" icon="el-icon-plus" @click="handleAdd" v-hasPermi="['labbase:receipt_form:edit']">发起流程</el-button>
      </el-form-item>
    </el-form>
    <em @click="fetchTemplate" style="cursor:pointer;color:blue;float:right;margin-top: -20px;">下载维修申请表模板</em>
    <el-table v-loading="loading" :data="receipt_formList">
      <el-table-column label="编号" prop="instanceId" width="60" align="center"/>
      <el-table-column label="流程名称" prop="flowName" :show-overflow-tooltip="true" />
      <el-table-column label="料单类型" prop="receiptTypeOpt" :formatter="receiptTypeOptFormat" align="center" width="80"/>
      <el-table-column label="创建用户" prop="createBy" width="80" align="center"/>
      <el-table-column label="创建时间" prop="createTime" width="150px" align="center"/>
      <el-table-column label="提交时间" prop="startTime" width="150px" align="center">
      </el-table-column>
      <el-table-column label="执行步骤" prop="nodeName" align="center" width="100" :show-overflow-tooltip="true" />
      <el-table-column label="结束时间" prop="endTime" width="150px" align="center"/>
      <el-table-column label="操作" align="center" width="100">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-if="scope.row.flowStatusOpt=='uncommitted'" v-hasPermi="['labbase:receipt_form:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-if="scope.row.flowStatusOpt=='uncommitted'" v-hasPermi="['labbase:receipt_form:edit']">删除</el-button>
          <el-button v-if="scope.row.flowStatusOpt!='uncommitted'" size="mini" type="text"
            @click="handlePreview(scope.row)">查看
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />
    <!-- 添加或修改单据对话框 -->
    <el-dialog :title="title" center :visible.sync="open" width="700px" append-to-body>
      <el-tabs v-model="activeName">
        <el-tab-pane label="流程表单" name="first" key="first"></el-tab-pane>
        <el-tab-pane label="资产明细" name="second" key="second" v-if="form.instanceId">
          <ReceiptDetails ref="details" :instanceId="form.instanceId" isEdit></ReceiptDetails>
        </el-tab-pane>
        <el-tab-pane label="填报说明" name="third" key="third">

          <button @click="fetchTemplate" style="cursor:pointer;color:blue">下载维修申请表模板</button>
          <img src="@/assets/image/receipt_note.png" width="600" border="0"/>
        </el-tab-pane>
        <el-tab-pane label="流程导入" name="fourth" key="fourth" v-if="form.instanceId">
          <FlowChoose ref="workFlow" @workflow="setWorkflow" :id="form.workflowId" :businessType="form.businessTypeOpt"></FlowChoose>
        </el-tab-pane>
      </el-tabs>
      <el-form ref="form" :model="form" :rules="form.receiptTypeOpt!=4?rules:rules1" label-width="100px" v-if="activeName=='first'">
        <el-row>
          <el-col>
            <el-form-item label="任务创建" prop="createTime">
              {{form.createTime}}<span style="margin-left: 20px;">由&nbsp;{{form.createBy}}&nbsp;创建&nbsp;&nbsp;</span>
            <div style="float:right">
              <el-button :class="showCopy?'dis_active':'active'" @click="showCopy=showCopy?false:true" type="text">任务抄送
              </el-button>
            </div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="任务抄送" prop="copyToUsers" v-show="showCopy">
          <div class="purchase_s_view">
            <el-input v-model="choosedUserName" placeholder="抄送人员" style="width: 426px;" />
            <el-button type="primary" @click="selectUser" plain>选择用户</el-button>
          </div>
        </el-form-item>
        <el-row>
          <el-form-item label="流程名称" prop="flowName">
            <el-input v-model="form.flowName" placeholder="请输入流程名称" class="form_long" />
          </el-form-item>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="料单类型" prop="receiptTypeOpt">
              <el-select v-model="form.receiptTypeOpt" placeholder="请选择料单类型" class="form_short">
                <el-option v-for="dict in receiptTypeOptOptions" :key="dict.dictValue" :label="dict.dictLabel"
                  :value="parseInt(dict.dictValue)"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

          <el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="经费项目" prop="fundsItem">
                  <el-input v-model="form.fundsItem" placeholder="经费项目" class="form_long" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-col :span="12">
              <el-form-item label="二级单位" prop="collegeOrgId">
                <el-select v-model="form.collegeOrgId" placeholder="请选择二级单位" class="form_short"
                  @change="handleLabChange">
                  <el-option v-for="item in secondOrgList" :key="item.orgName" :label="item.orgName"
                    :value="item.orgId">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="实验室" prop="labId">
                <el-select v-model="form.labId" placeholder="请选择实验室" class="form_short" @change="refreshChoose">
                  <el-option v-for="item in secondOrgLabList" :key="item.orgName" :label="item.orgName"
                    :value="item.orgId"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
             <el-form-item label="使用方向" prop="expectUseOpt">
               <el-select v-model="form.expectUseOpt" placeholder="请选择使用方向" class="form_short">
                 <el-option v-for="dict in expectUseOptOptions" :key="dict.dictValue" :label="dict.dictLabel"
                   :value="dict.dictValue"></el-option>
               </el-select>
             </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="填单日期" prop="fillDate">
                <el-date-picker clearable size="small" v-model="form.fillDate" type="date" value-format="yyyy-MM-dd"
                  placeholder="选择填单日期" style="width: 200px;">
                </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="发票日期" prop="purchaseDate">
                <el-date-picker clearable size="small" v-model="form.purchaseDate" type="date" value-format="yyyy-MM-dd"
                  placeholder="选择发票日期" style="width: 200px;">
                </el-date-picker>
              </el-form-item>
            </el-col>
           <el-col :span="12">
             <el-form-item label="发票号" prop="voucherNo">
               <el-input v-model="form.voucherNo" placeholder="请输入发票号" class="form_short" />
             </el-form-item>

           </el-col>
          </el-row>
          <el-row>
            <el-form-item label="公司名称" prop="manufactor">
              <el-input v-model="form.manufactor" placeholder="请输入公司名称" class="form_long" />
            </el-form-item>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="收料人员" prop="receiptorId">
                <el-input v-model="form.receiptorId" placeholder="请输入收料人员" class="form_short" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="经办人员" prop="handlingUserId">
                <el-input v-model="form.handlingUserId" placeholder="请输入经办人员工号" class="form_short" @blur="searchUser"
                  @keyup.enter.native="searchUser" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="经办人姓名" prop="contactUser">
                <el-input v-model="form.contactUser" placeholder="自动带入" disabled class="form_short" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="经办人电话" prop="contactMobile">
                <el-input v-model="form.contactMobile" placeholder="自动带入" disabled class="form_short" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="备注说明" prop="comments">
            <el-input v-model="form.comments" type="textarea" :placeholder="form.receiptTypeOpt==4?'价值超1000元请上传维修清单':form.receiptTypeOpt==2?'超1000元属于固定资产范畴，不需要提交料单':'请输入备注' " class="form_long" rows="4" />
          </el-form-item>
        <el-form-item label="附件" prop="taskDescription">
          <UploadCom ref="upload" @submitData="submitData" :description="'请上传发票以及'+(form.receiptTypeOpt!=4?'付款记录、采购合同等文件':'仪器和设备维修申请表')" :userFileList="fileList"
            class="form_long" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" v-if="activeName=='first'">保存</el-button>
        <el-button type="primary" @click="submitWorkflow" v-if="activeName=='fourth' || activeName=='second'">提交</el-button>
        <el-button @click="cancel">关闭</el-button>
      </div>
    </el-dialog>
    <ChooseUser @chooseUsers="getUser" ref="checkedUserCom"></ChooseUser>
    <ReceiptPreview ref="preview" @refresh="getList"></ReceiptPreview>
  </div>
</template>

<script>
  import {
    commitReceipt,
    listReceipt_form,
    getReceipt_form,
    delReceipt_form,
    addReceipt_form,
    updateReceipt_form,
    exportReceipt_form,
  } from "@/api/labbase/receipt_form";
  import {
    formatCurrentDate,menoyToUppercase
  } from "@/utils/index";
  import {
    searchEmployee,
    getCheckedList
  } from "@/api/labdata/employee"
  import {
    getOrgByFunctionOpt,
    listSecondOrgLab
  } from "@/api/labdata/orgnization";
  import FlowChoose from '@/views/labdata/flowDefination/flow_choose.vue'
  import ChooseUser from "@/views/labdata/employee/user_choose_com.vue";
  import UploadCom from "@/views/labdata/commons/upload.vue";
  import ReceiptPreview from "@/views/labbase/receipt_form/receipt_preview.vue";
  //import RepairedDevice from "@/views/labdata/repairedDevice/index.vue";
  import ReceiptDetails from "@/views/labbase/receipt_form/details.vue";
  export default {
    name: "Receipt_form_compact",
    components: {
      ChooseUser,
      FlowChoose,
      UploadCom,
      ReceiptPreview,
     // RepairedDevice,
      ReceiptDetails
    },
    data() {
      return {
        activeName: "first",
        checkedUserList: [],
        choosedUserName: '',
        // 料单类型字典
        receiptTypeOptOptions: [],
        expectUseOptOptions: [],
        // 流程状态字典
        flowStatusOptOptions: [],
        showCopy: false,
        // 遮罩层
        loading: true,
        // 总条数
        total: 0,
        // 单据表格数据
        receipt_formList: [],
        //二级机构
        secondOrgList: [],
        //二级机构下的实验室
        secondOrgLabList: [],
        //附件集合
        fileList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          flowName: null,
        },
        // 表单参数
        form: {
        },
        // 表单校验
        rules: {
          createTime: [{
            required: true,
            message: "创建时间不能为空",
            trigger: "blur"
          }, ],
          createBy: [{
            required: true,
            message: "创建人不能为空",
            trigger: "blur"
          }, ],
          flowName: [{
            required: true,
            message: "流程名称不能为空",
            trigger: "blur"
          }, ],
          receiptTypeOpt: [{
            required: true,
            message: "料单类型不能为空",
            trigger: "blur"
          }, ],
          collegeOrgId: [{
            required: true,
            message: "学院不能为空",
            trigger: "blur"
          }, ],

          purchaseDate: [{
            required: true,
            message: "购置日期不能为空",
            trigger: "blur"
          }, ],
          fillDate: [{
            required: true,
            message: "填单日期不能为空",
            trigger: "blur"
          }, ],
          expectUseOpt: [{
            required: true,
            message: "使用方向不能为空",
            trigger: "blur"
          }, ],
          originalVoucher: [{
            required: true,
            message: "原始凭证不能为空",
            trigger: "blur"
          }, ],
          voucherNo: [{
            required: true,
            message: "凭证编号不能为空",
            trigger: "blur"
          }, ],
          contactUser: [{
            required: true,
            message: "联系人不能为空",
            trigger: "blur"
          }, ],
         /* contactMobile: [{
            required: true,
            message: "联系电话不能为空",
            trigger: "blur"
          }, ], */
        },
        rules1: {
          createTime: [{
            required: true,
            message: "创建时间不能为空",
            trigger: "blur"
          }, ],
          createBy: [{
            required: true,
            message: "创建人不能为空",
            trigger: "blur"
          }, ],
          flowName: [{
            required: true,
            message: "流程名称不能为空",
            trigger: "blur"
          }, ],
          receiptTypeOpt: [{
            required: true,
            message: "料单类型不能为空",
            trigger: "blur"
          }, ],
        }
      };
    },
    watch: {
      checkedUserList: function(val) {
        this.choosedUserName = '';
        this.form.copyToUsers = '';
        val.forEach((item, index) => {
          if (index > 0) {
            this.choosedUserName += ",";
            this.form.copyToUsers += ",";
          }
          this.choosedUserName += item.nickName;
          this.form.copyToUsers += item.userId;
        })
      },
    },
    created() {
      this.getList();
      this.getDicts("receiptTypeOpt").then((response) => {
        this.receiptTypeOptOptions = response.data;
      });
      this.getDicts("expectUseOpt").then((response) => {
        this.expectUseOptOptions = response.data;
      });
      getOrgByFunctionOpt(2).then(response => {
        this.secondOrgList = response.data;
      });
      this.getDicts("flowStatusOpt ").then(response => {
        this.flowStatusOptOptions = response.data;
      });
    },
    methods: {
      fetchTemplate() {
        window.open("/lab/新版维修申请表.doc");
      },
      handlePreview(row) {
        this.$refs["preview"].handleUpdate(row);
      },
	  selectUser(){
      if(this.checkedUserList && this.checkedUserList.length>0){
        this.$refs["checkedUserCom"].handleAdd(this.checkedUserList);
      }else{
         this.$refs["checkedUserCom"].handleAdd();
      }
	  },
      getUser(e) {
        //console.log(JSON.stringify(e));
        this.checkedUserList = e;
      },
      setWorkflow(workflowId) {
        this.form.workflowId = workflowId;
        //console.log('workflow='+workflowId);
      },
      submitWorkflow() {
		if(!this.form.workflowId){
		    this.form.workflowId = this.$refs["workFlow"].getWorkflowId();
		}
        if(this.activeName=='second'){
          this.activeName = 'fourth';
        }else if(this.activeName = 'fourth'){
          commitReceipt(this.form).then((response) => {
            this.msgSuccess("提交成功");
            this.open = false;
            this.getList();
          });
        }
      },
      searchUser() {
        if (!this.form.handlingUserId) {
          this.form.contactUser = null;
          this.form.contactMobile = null;
          return;
        } else
          searchEmployee(this.form.handlingUserId).then(response => {
            let searchResult = response.data;
            if (searchResult) {
              this.form.contactUser = searchResult.nickName;
              this.form.contactMobile = searchResult.phonenumber;
            } else {
              this.form.contactUser = null;
              this.form.contactMobile = null;
            }
            this.$forceUpdate();
          });

      },
      // 流程状态字典翻译
      flowStatusOptFormat(row, column) {
        return this.selectDictLabel(this.flowStatusOptOptions, row.flowStatusOpt);
      },
      // 料单类型字典翻译
      receiptTypeOptFormat(row, column) {
        return this.selectDictLabel(this.receiptTypeOptOptions, row.receiptTypeOpt);
      },
      handleLabChange(item) {
        //console.log('change lab :'+item);
        if (item) {
          this.form.labId = null;
          listSecondOrgLab(item).then(response => {
            this.secondOrgLabList = response.data;
          });
        }
      },
      refreshChoose() {
        this.$forceUpdate();
      },
      /** 查询单据列表 */
      getList() {
        this.loading = true;
        listReceipt_form(this.queryParams).then((response) => {
          this.receipt_formList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
        this.showCopy = false;
        this.activeName = 'first';
        this.fileList = [];
        this.getList();
      },
      // 表单重置
      reset() {
        this.form = {};
        this.activeName = 'first';
        this.fileList = [];
        this.checkedUserList = [];
        this.resetForm("form");
        this.form.createTime = formatCurrentDate();
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.queryParams = {
          pageNum: 1,
          pageSize: 10,
        };
        this.resetForm("queryForm");
        this.handleQuery();
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.form.createBy = this.$store.state.user.name;
        this.open = true;
        this.title = "添加单据";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const instanceId = row.instanceId || this.ids;
        getReceipt_form(instanceId).then((response) => {
          this.form = response.data;
          this.fileList = this.form.images;
          if(this.form.collegeOrgId)
          listSecondOrgLab(this.form.collegeOrgId).then(response => {
            this.secondOrgLabList = response.data;
            this.$forceUpdate();
          });
		  if(this.form.copyToUsers!=null && this.form.copyToUsers!=''){
		    getCheckedList({checkedUserIds:this.form.copyToUsers}).then(res=>{
		      this.checkedUserList = res.data;
		      this.showCopy = true;
		    });
		  }
          this.open = true;
          this.title = "修改单据";
        });
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            this.$refs["upload"].doSubmit();
          }
        });
      },
      /** 提交按钮 */
      submitData(allFiles) {
        this.form.images = allFiles;
        //device
       /* if(this.form.receiptTypeOpt==4){
          this.form.repairedDevice = this.$refs["device"].getDevice();
        } */
        //console.log(this.form);
        if (this.form.instanceId != null) {
          updateReceipt_form(this.form).then((response) => {
            this.msgSuccess("修改成功");
            this.form = response.data;
            this.fileList = this.form.images;
            //if(this.form.receiptTypeOpt!=4){
              this.activeName = 'second';
            //}
            this.$forceUpdate();
            //this.open = false;
            //this.getList();
          });
        } else {
          addReceipt_form(this.form).then((response) => {
            this.msgSuccess("新增成功");
            this.form = response.data;
            this.fileList = this.form.images;
            //this.open = false;
            //this.getList();
           // if(this.form.receiptTypeOpt!=4){
              this.activeName = 'second';
           // }
          });
        }

      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const instanceIds = row.instanceId || this.ids;
        this.$confirm(
            '是否确认删除单据编号为"' + instanceIds + '"的数据项?',
            "警告", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning",
            }
          )
          .then(function() {
            return delReceipt_form(instanceIds);
          })
          .then(() => {
            this.getList();
            this.msgSuccess("删除成功");
          });
      },
      setUpperMoney(){
        this.form.originalVoucher=menoyToUppercase(this.form.totalPrice);
        this.$forceUpdate();
      },
    },
  };
</script>
<style type="text/css" scoped>
  .form_long {
    width: 525px;
  }

  .form_short {
    width: 200px;
  }

 /deep/ .el-button.active {
    text-decoration: underline;
    color: #0000ee;
  }

  .hintItem {
    line-height: 30px;
  }

  .purchase_s_view {
    display: flex;
    flex-direction: row;
    align-items: center;
  }
</style>
